﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.ObjectModel;
using System.Reflection;

namespace Intersoft.Controls.TreeGridAssist
{
    public class TreeGridDataSource
    {
        public string IdField { get; set; }
        public string ParentIdField { get; set; }
        public IList OriginalSource { get; private set; }
        public ObservableCollection<TreeGridNodeItem> Source { get; private set; }

        public TreeGridDataSource(IList originalSource, ITreeBuilder treeBuilder)
        {
            Init(originalSource, treeBuilder);
        }

        public TreeGridDataSource()
        {
        }

        public TreeGridDataSource(IList originalSource)
        {
            Init(originalSource, new FlatTreeBuilder());
        }

        private void Init(IList originalSource, ITreeBuilder treeBuilder)
        {
            OriginalSource = originalSource;

            IdField = "Id";
            ParentIdField = "ParentId";
            IList<TreeGridNodeItem> tree = treeBuilder.BuildTree(this, originalSource);
            Source = GetRootNodes(tree);
        }

        private ObservableCollection<TreeGridNodeItem> GetRootNodes(IList<TreeGridNodeItem> tree)
        {
            ObservableCollection<TreeGridNodeItem> list = new ObservableCollection<TreeGridNodeItem>(tree);
            return list;
        }

        internal void NotifyIsExpandedChanged(TreeGridNodeItem item)
        {
            if (!item.IsExpanded)
            {
                RemoveSourceChildren(item);
            }
            else
            {
                int index = Source.IndexOf(item);
                AddSourceChildren(item, ref index);
            }
        }

        private void AddSourceChildren(TreeGridNodeItem item, ref int index)
        {
            foreach (var child in item.Children)
            {
                Source.Insert(++index, child);
                if (child.IsExpanded)
                {
                    AddSourceChildren(child, ref index);
                }
            }
        }

        private void RemoveSourceChildren(TreeGridNodeItem item)
        {
            foreach (var child in item.Children)
            {
                Source.Remove(child);
                RemoveSourceChildren(child);
            }
        }
    }
}
